#!/bin/bash
# move function

root="Público/SSOO-grupo6/directorios"
LOGGER_EXE="perl ./$root/BINDIR/Logger.pl"
#defines

moverW5()
{
if [ $# -gt 3 ]; then
	$LOGGER_EXE -m="Demasiados argumentos. Usage: moverW5 <sourceFile> <destFolder> [commandInvoked]" -e -c="004" -l="mover.sh" #log too many arguments
	#exit 1
fi

if [ $# -lt 2 ]; then
	$LOGGER_EXE -m="pocos argumentos. Usage: moverW5 <sourceFile> <destFolder> [commandInvoked]" -e -c="004" -l="mover.sh" #log not enough arguments
	#exit 1
fi

if [ ! -d "$2" ]; then
	$LOGGER_EXE -m="Archivo o directorio inexistente \"$2\"." -e -c="005" -l="mover.sh" #log invalid file
	#exit 1
fi

commandUsed=""
source_filename="${1##*/}"
source_directory="${1%/*}"
dest_path="$2"
if [ ! -d "$source_directory" ]; then
	$LOGGER_EXE -m="Archivo o directorio inexistente \"$source_directory\"." -e -c="005" -l="mover.sh" #log invalid file
	#exit 1
fi

if [ $(echo $2 | grep '.*/$' | wc -l) -eq 0 ]; then
	dest_path=${2}/  # 2nd arguments doesnt have a bar..adding it
fi

if [ $# -eq 3 ]; then
	commandUsed=$3
fi

if [ -f "$1" ]; then # source file exists
  	if [ -f "${dest_path}${source_filename}.0" ]; then # source file exists in destination folder
		sequence_number=$(ls $dest_path -1 | grep "^$source_filename.[0-9][0-9]*" | wc -l)
		mv $1 "${dest_path}${source_filename}.$sequence_number" # muevo agregando la extension
	else
		mv $1 "${dest_path}${source_filename}.0"
	fi
	if [ "$commandUsed" -eq "" ]; then
		$LOGGER_EXE -m="Funcion mover exitosa." -i -c="005" -l="mover.sh" #log successful move
	else
		$LOGGER_EXE -m="Funcion mover exitosa en ambiente $commandUsed." -i -c="005" -l="mover.sh" #log successful move
	fi
else
	$LOGGER_EXE -m="Archivo o directorio inexistente \"$1\"." -e -c="005" -l="mover.sh" #log invalid file
	#exit 1
fi
#exit 0
}

export -f moverW5
